package com.lhn.juc;

import java.util.concurrent.*;

/**
 * Semaphore demo
 *
 * @author lhn
 * @date 2022/09/21 21:33
 * @since 1.0.0
 **/
public class SemaphoreTest {

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(3);
        final Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("子线程" + Thread.currentThread().getName() + "开始执行");
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("子线程" + Thread.currentThread().getName() + "执行完成");
                semaphore.release();//当前线程调用此方法，则计数减一
            }, "Thread" + i);
            service.execute(thread);
        }
    }

}